import Cookies from 'js-cookie'
const state = {
    bookId: get("bookId"),
    book: getObj("book"),
    chapter: getObj("chapter") ,
    bookActiveId: get('bookActiveId') ,
    bookActiveIndex: get('bookActiveIndex') || '0',
    learnCtSidebarRefresh: Cookies.get("learnCtSidebarRefresh") ,
    learnHomeActiveId: Cookies.get("learnHomeActiveId") || "0" ,
    site: Cookies.get("site") ,
}

function getObj(key){
    let val = get(key)
    if(val != null){
        return JSON.parse(val)
    }
    return  {}
}
function get(key){
    return localStorage.getItem(key)
}
function set(key ,val){
    if(typeof val == "object"){
        localStorage.setItem(key , JSON.stringify(val))
    }else{
        localStorage.setItem(key , val)
    }

}
const mutations = {
    setBookId(state , bookId){
        set("bookId", bookId)
        state.bookId = bookId ;
    },
    setBook(state, val) {
        set("book", val)
        state.book = val ;
    },
    setChapter(state, val){
        set("chapter", val)
        state.chapter = val ;
    },
    setBookActiveId(state, val){
        state.bookActiveId = val
        set("bookActiveId", val)
    },
    setBookActiveIndex(state, val){
        state.bookActiveIndex = val
        set("bookActiveIndex", val)
    },
    setLearnCtSidebarRefresh(state){
        state.learnCtSidebarRefresh = Date.now() ;
        Cookies.set("learnCtSidebarRefresh",state.learnCtSidebarRefresh)
    },
    setLearnHomeActiveId(state , val){
        Cookies.set("learnHomeActiveId",val)
        state.learnHomeActiveId = val ;
    },
    setSite(state , site){
        Cookies.set("site",site)
        state.site = site ;
    }
}

const actions = {

}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
